package com.blockmeta.bbs.minemodule.widget

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil

/**
 * @author AirThor
 * @date 2018/10/30.
 */
class PercentViewGamble : View{
    //看涨画笔
    val mUpPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    //看跌画笔
    val mDownPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    //两端保留的最小宽度 当比例为零时也会保持这个宽度 不会全部消失
    val minWidth = DimentionsUtil.dp2px(context,20f)
    //衔接处为倾斜的 所以定义一个斜率表示多出来的部分
    val mSlopRatio = 0.6
    var mSlop = 0f
    //两端的圆角半径
    var mCornerRadius = 0f
    //看涨看跌的百分比
    var mPercentUp = 0.5f
    var mPercentDown = 0.5f
    //两个图之间的缝隙
    val gap = DimentionsUtil.dp2px(context,4f)
    //
    val upPath = Path()
    val downPath = Path()
    lateinit var mRectUp: RectF
    lateinit var mRectDown: RectF

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    init {
        mUpPaint.color = Color.parseColor("#53ce85")
        mDownPaint.color = Color.parseColor("#f24956")
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mSlop = (h/mSlopRatio).toFloat()
        mCornerRadius = h/2f
        mRectUp = RectF(0f,0f,mCornerRadius*2,mCornerRadius*2)
        mRectDown = RectF(w-mCornerRadius*2,0f,w.toFloat(),mCornerRadius*2)

    }
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val upWidth = (measuredWidth-mCornerRadius*2-gap-mSlop)*mPercentUp
        val downWidth = measuredWidth-mCornerRadius*2-gap-mSlop-upWidth
        upPath.addArc(mRectUp,90f,180f)
        upPath.lineTo(mCornerRadius+upWidth+mSlop,0f)
        upPath.lineTo(mCornerRadius+upWidth,measuredHeight.toFloat())
        canvas.drawPath(upPath,mUpPaint)

        downPath.moveTo(mCornerRadius+upWidth+mSlop+gap,0f)
        downPath.lineTo(mCornerRadius+upWidth+mSlop+gap+downWidth,0f)
        downPath.arcTo(mRectDown,270f,180f)
        downPath.lineTo(mCornerRadius+upWidth+gap,measuredHeight.toFloat())
        canvas.drawPath(downPath,mDownPaint)
    }

    fun setPercent(percent: Float){
        mPercentUp = percent
        mPercentDown = 1-percent
        postInvalidate()
    }
}